<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="内部单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入内部单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="线上订单号" prop="orderLineNo">
        <el-input v-model="queryParams.orderLineNo" placeholder="请输入线上订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="生产状态" prop="orderProduceStatus">
        <el-select v-model="queryParams.orderProduceStatus" placeholder="请选择" style="width: 200px">
          <el-option :label="item.label" :value="item.value" v-for="(item,index) in orderProduceStatus_type" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleImport">导入</el-button>
        <!--        <el-button type="primary" plain icon="Download">导出</el-button>
        <el-button type="primary" plain icon="Download">导出明细</el-button>
        <el-button type="primary" plain icon="Download">发货</el-button>
        <el-button type="primary" plain icon="Download">取消</el-button>
        <el-button type="primary" plain icon="Download">变类型</el-button>
        <el-button type="primary" plain icon="Download">获取TEMU订单</el-button> -->
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="groupList">
      <el-table-column type="selection" width="55" />
      <el-table-column label="内部单号" prop="orderNo">
        <template #default="scope">
          <router-link :to="'/order/orderDetail?orderNo=' + scope.row.orderNo" class="link-type">
            <span>{{ scope.row.orderNo }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="商品" prop="goodsImageUrl" :show-overflow-tooltip="true" width="160">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" v-if="scope.row.detailsList" :src="scope.row.detailsList.goodsImageUrl" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="件数" prop="orderTotalNum" :show-overflow-tooltip="true" width="50">
        <template #default="scope">
          <div style="display: flex;align-items: center;">
            {{scope.row.orderTotalNum}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单备注" prop="remark" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="买家留言" prop="orderBuyerMessage" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="付款日期" prop="payTime" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="付款金额" prop="payAmount" :show-overflow-tooltip="true" width="100"></el-table-column>
      <el-table-column label="店铺名称" align="center" width="100" prop="shopsName"></el-table-column>
      <el-table-column label="生产状态" align="center" width="200" prop="orderProduceStatus"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template #default="scope">
          <el-button link type="primary" @click="handleFaHuo(scope.row)">发货</el-button>
          <el-button link type="primary" @click="handleCancel(scope.row)">取消</el-button>
          <el-button link type="primary" @click="handleChange(scope.row)">变类型</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改物料配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="cancelRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="取消原因" prop="orderStatusType">
          <el-select v-model="form.orderStatusType" placeholder="请选择取消原因" clearable style="width: 200px">
            <el-option v-for="dict in orderStatusType_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.orderStatusRemark" type="textarea" placeholder="备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCancelForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改物料配置对话框 -->
    <el-dialog title="变类型" v-model="TypeOpen" width="700px" append-to-body>
      <el-form ref="cancelRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="订单类型" prop="orderType">
          <el-radio-group v-model="form.orderType" placeholder="请选择取消原因" clearable style="width: 200px">
            <el-radio v-for="dict in orderType_type" :key="dict.value" :label="dict.label" :value="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="sumbitchangeType">确 定</el-button>
          <el-button @click="TypeOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 订单导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="500px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :data="{ type: 0, tenantGroupId: tenantGroupId }" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <a :href="templatePath" style="color: #409EFF;" download>点击下载导入模板</a>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="order">
  import {
    list,
    orderDeliver,
    orderCancel,
    orderTypeEdit
  } from "@/api/order/order"
  import {
    listapplicant,
  } from "@/api/system/applicant";
  import baseForm from "../hooks/useOrderBase";
  const { headers, tenantGroupId } = baseForm();
  const router = useRouter();
  const route = useRoute()
  const { proxy } = getCurrentInstance();
  const { orderProduceStatus_type, orderStatusType_type, orderType_type } = proxy.useDict("orderProduceStatus_type", "orderStatusType_type", "orderType_type");
  const groupList = ref([]);
  const open = ref(false);
  const TypeOpen = ref(false)
  const appLicationList = ref([])
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const templatePath = ref('./导入模板.xlsx')
  const title = ref("");
  const dateRange = ref([])
  /*** 订单导入参数 */
  const upload = reactive({
    // 是否显示弹出层（订单导入）
    open: false,
    // 弹出层标题（订单导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的订单数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: headers,
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/system/order/importData"
  });

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      orderNo: '',
      orderLineNo: undefined,
      shopsId: undefined,
      orderProduceStatus: '',
    },
    rules: {

    },
  });
  const { queryParams, form, rules } = toRefs(data);
  /**文件上传中处理 */
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
  };
  /** 导入按钮操作 */
  function handleImport() {
    upload.title = "订单导入";
    upload.open = true;
  };
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>",
      "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  };

  /** 提交上传文件 */
  function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
  };
  /** 查询订单列表 */
  function getList() {
    loading.value = true;
    let formQueryParam = { ...queryParams.value };
    formQueryParam.orderProduceStatus = formQueryParam.orderProduceStatus == 0 ? '' : formQueryParam.orderProduceStatus
    list(proxy.addDateRange(formQueryParam, dateRange.value)).then(response => {
      groupList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      orderProduceStatus: '',
      orderName: undefined,
      orderLinkName: undefined,
      orderLinkMobile: '',
      orderExpireStatus: '',
      orderAvl: ''
    }
    handleQuery();
  }
  /** 删除按钮操作 */
  function handleFaHuo(row) {
    proxy.$modal.confirm('是否确认发货订单编号为"' + row.orderNo + '"的数据项?').then(function() {
      return orderDeliver({ id: row.id });
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    }).catch(() => {});
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const orderIds = row.orderId || ids.value;
    proxy.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项?').then(function() {
      return delgroup(orderIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }

  /** 重置新增的表单以及其他数据  */
  function reset() {
    form.value = {

    };
    proxy.resetForm("roleRef");
  }
  /** 订单变更 */
  function handleChange(row) {
    reset();
    form.value = { ...row }
    TypeOpen.value = true;
    title.value = "订单类型变更";
  }
  /** 订单取消 */
  function handleCancel(row) {
    reset();
    form.value = { ...row }
    open.value = true;
    title.value = "订单取消";
  }

  /** 修改订单 */
  function handleUpdate(row) {
    reset();
    const orderId = row.orderId || ids.value;
    getgroup(orderId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改订单";
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }

  function sumbitchangeType() {
    orderTypeEdit({
      id: form.value.id,
      orderType: form.value.orderType
    }).then(response => {
      proxy.$modal.msgSuccess("变更成功");
      TypeOpen.value = false;
      getList();
    });
  }

  function submitCancelForm() {
    proxy.$refs["cancelRef"].validate(valid => {
      if (valid) {
        orderTypeEdit({
          id: form.value.id,
          orderStatusType: form.value.orderStatusType,
          orderStatusRemark: form.value.orderStatusRemark
        }).then(response => {
          proxy.$modal.msgSuccess("取消成功");
          open.value = false;
          getList();
        });
      }
    });
  }
  getList();
</script>